package com.lh.java.basic.threadlocal;

import java.util.Random;

public class ThreadDemo implements Runnable {
	Student student = new Student();
	private int count=0; 

	public static void main(String[] agrs) {
		ThreadDemo td = new ThreadDemo();
		Thread t1 = new Thread(td, "a");
		Thread t2 = new Thread(td, "b");
		t1.start();
		t2.start();
		Math.random();
	}

	public void run() {
		
			accessStudent();
		
	}

	public void accessStudent() {		
		String currentThreadName = Thread.currentThread().getName();
		System.out.println(currentThreadName + " is running!");
		
		try {
			  this.count++;
			  Thread.sleep(1000);
			}catch(InterruptedException ex) {
			  ex.printStackTrace();
			}
		System.out.println("thread "+currentThreadName+" read count:"+this.count); 
		
		synchronized (this) {Random random = new Random();
		int age = random.nextInt(100);
		System.out
				.println("thread " + currentThreadName + " set age to:" + age);
		student.setAge(age);
		System.out.println("thread " + currentThreadName
				+ " first read age is:" + student.getAge());

		try {
			Thread.sleep(1000);
		} catch (InterruptedException ex) {
			ex.printStackTrace();
		}
		System.out.println("thread " + currentThreadName
				+ " second read age is:" + student.getAge());
	 }
	}
	

}

class Student {
	private int age = 0;

	public int getAge() {
		return this.age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	protected void finalize() throws Throwable {		
		super.finalize();
		System.out.println("i am finalize");
	}
	
}
